<?php
$loader->requireOnce('includes/EnumerationConstant.class.php');
$loader->requireOnce('includes/inPatientCore/InPatientCoreErrorCode.class.php');
$loader->requireOnce('includes/inPatientCore/InPatientCoreException.class.php');

$loader->requireOnce('ordo/Ticket.class.php');

/**
 * Inpatient entity.
 * @package core.ordo
 * @author viethd
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class InPatient extends ORDataObject {

	/**#@+
	 * Fields of table: in_patient mapped to class members
	 */
	var $in_patient_id		= '';
	var $ticket_id		= '';
	var $enum_status		= '';
	var $department_id		= '';
	/**#@-*/


	/**
	 * DB Table
	 */
	var $_table = 'in_patient';

	/**
	 * Primary Key
	 */
	var $_key = 'in_patient_id';

	/**
	 * Internal Name
	 */
	var $_internalName = 'InPatient';

	 function __construct() {
        parent::ORDataObject();
    }
    /**
     * Get the Key for an enum based on it's value.
     * @param  number $departmentId Deparment Id
     * @param  EnumerationConstant $enumStatus inpatient status
     * @return array[n](in_patient_id, patient_name, ticket_id,
     *  enum_status, patient_code, relative_name, check_in_time)
     * @throw CoreException  enumStatus not supported
     */
    public function listOfCheckInPatientItemByStatus($departmentId, $enumStatus) {

    	$field =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');
        
        $ds = new Datasource_sql();        
        $statusCond = "";
        if ($enumStatus == EnumerationConstant::PATIENT_SUB_STATUS_ALL) {
            $statusCond = "";
        } else  {
            $arrStatus = Utils::getEnumKey( EnumerationConstant::PATIENT_SUB_STATUS, $enumStatus);
            $statusCond = " AND IP.enum_status = $arrStatus";             
        }
        $sql = array(
            'cols'  => "distinct IP.in_patient_id in_patient_id, PE.name patient_name, T.patient_id patient_id, T.department_id  department_id, IP.ticket_id ticket_id, IP.enum_status enum_status,
                    PA.patient_code patient_code, PA.relative_name  relative_name, T.started check_in_time, r.$field as room_name, b.code as bed_code",
            'from'  => " in_patient IP " .
                    " INNER JOIN ticket T ON IP.ticket_id = T.ticket_id " .
                    " INNER JOIN patient PA ON T.patient_id = PA.person_id " .
                    " INNER JOIN person PE ON T.patient_id = PE.person_id
                      LEFT JOIN patient_bed pb ON  (pb.current = 1 AND T.ticket_id = pb.ticket_id)
                      LEFT JOIN bed b ON (b.bed_id != 1 AND b.deleted = 0 AND b.bed_id = pb.bed_id)
                      LEFT JOIN room r ON r.room_id = b.room_id",
            'where' => "IP.department_id = $departmentId " . $statusCond,
            'orderby'   => "T.started"
            );

        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        return $result;
    }

    public function listInPatientInCashierQueue($departmentId, $enumStatus) {
        $field  =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');        
        $dateFormat =   L10nHelper::getSqlDateFormat();

        $ds = new Datasource_sql();
        $em = EnumManager::getInstance();
        $statusCond = "";
        if ($enumStatus == EnumerationConstant::PATIENT_SUB_STATUS_ALL) {
            $statusCond = "";
        } else  {
            $arrStatus = Utils::getEnumKey( EnumerationConstant::PATIENT_SUB_STATUS, $enumStatus);
            $statusCond = " AND IP.enum_status = $arrStatus";            
        }
        $sql = array(
            'cols'  => "distinct IP.in_patient_id in_patient_id, PE.name patient_name, T.patient_id patient_id, 
                    T.department_id  department_id, IP.ticket_id ticket_id, IP.enum_status enum_status,
                    PA.patient_code patient_code, DATE_FORMAT(T.started,'$dateFormat') check_in_time, 
                    T.insurance insurance, d.$field department_name",
            'from'  => " in_patient IP " .
                    " INNER JOIN ticket T ON IP.ticket_id = T.ticket_id " .
                    " INNER JOIN patient PA ON T.patient_id = PA.person_id " .
                    " INNER JOIN person PE ON T.patient_id = PE.person_id
                      LEFT JOIN department d ON T.department_id=d.department_id",
            'where' =>"1 ",
            'orderby'   => "patient_name"
            );
        if ($departmentId) {
        	$sql['where']  .=  " AND IP.department_id='$departmentId'";
        }
        if (!empty($statusCond)) {
        	$sql['where']  .=  " AND $statusCond";
        }
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        return $result;
    }

    /**
     *Change status of inPatient on queue.
     *@param $ticketId
     *@param $enumStatus
     *@throw CoreException  enumStatus not supported
     *
     */
    // TODO REVIEW Trung Nguyen 2009-07-21
    // Missing function modifier
    public function changeCheckinPatientItemStatus($ticketId, $enumStatus) {
        $em = EnumManager::getInstance();
        $arrStatus = Utils::getEnumKey(EnumerationConstant::PATIENT_SUB_STATUS, $enumStatus);
        $data = array('enum_status' => $arrStatus);
        $sql = "UPDATE $this->_table SET enum_status=$arrStatus WHERE ticket_id =$ticketId";
        $this->_execute($sql);
    }
    /**
     * Remove inpatient has [$ticketId] from inPatient queue.
     *  @param $ticketId
     * @return unknown_type
     */
    public function removeCheckinPatientItem($ticketId) {
        $em = EnumManager::getInstance();
        $sql = "DELETE FROM $this->_table WHERE ticket_id =$ticketId";
        $this->_execute($sql);
    }

    /**
     * Close a ticket and remove it from inpatient queue.
     * @param $ticketId
     * @return unknown_type
     */
    public function finalizeInpatient($ticketId) {
        $sql = "update ticket set status='" . Ticket::CLOSED_STATUS . "', closed = NOW() where ticket_id = $ticketId";
        $this->_execute($sql);
        $this->removeCheckinPatientItem($ticketId);
    }
    /**
     * add new ticket for an inpatient.
     * @param $ticketId
     * @param $departmentId
     * @param $subStatus
     * @return unknown_type
     */
    public function addNewInpatient($ticketId, $departmentId, $subStatus) {
    	$data = array('ticket_id'=>$ticketId,
                      'department_id'=>$departmentId,
                      'enum_status'=>$subStatus);
       $this->populateArray($data);
       $this->persist();

    }
    /**
     * Check wherether this inpatient exist or not.
     * @param $patientId
     * @return
     * true : exist
     * <br>
     * false : not exist
     */
    public function isPatientExisted($patientId) {
    	$ds = new Datasource_sql();
        $sql = array(
            'cols'  => "IP.in_patient_id",
            'from'  => " in_patient IP " .
                    " INNER JOIN ticket T ON IP.ticket_id = T.ticket_id ",
            'where' => "T.patient_id = $patientId"
            );
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        if (empty($result)) {
        	return false;
        }
        return true;
    }

    /**
     * Count the number of patient of specified department.
     * This is used for resident patients only
     *
     * @param $departmentId the department id
     * @return int, number of patients in that department
     */
	public function countPatientNumber($departmentId) {
		$ds = new Datasource_sql();
		$sql = array(
			'cols'	=> "COUNT(inp.ticket_id) AS patient_number",
			'from'	=> "$this->_table inp
					INNER JOIN ticket t ON inp.ticket_id = t.ticket_id",
			'where'	=> "inp.department_id = $departmentId");
		$ds->setup($this->_db, $sql);
		$res = $ds->toArray('patient_number');
		return $res[0];
	}

	/**
	 * Get information of an inpatient by given patient Id.
	 *
	 * @param int $patienId Patient Id
	 * return array Array of result info
	 */
	public function getInPatientInfo($patienId) {
	    $field =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');        
        $dateFormat =   L10nHelper::getSqlDateFormat();
        $ds = new Datasource_sql();

		$sql = array(
            'cols'  => "distinct IP.in_patient_id in_patient_id, PE.name patient_name,
                        DATE_FORMAT(PE.date_of_birth,'$dateFormat') date_of_birth,
                        T.patient_id patient_id, T.department_id  department_id, PA.patient_code patient_code,
                        DATE_FORMAT(T.started,'$dateFormat') check_in_time, T.insurance insurance, d.$field department_name",
            'from'  => " in_patient IP " .
                    " INNER JOIN ticket T ON IP.ticket_id = T.ticket_id " .
                    " INNER JOIN patient PA ON T.patient_id = PA.person_id " .
                    " INNER JOIN person PE ON T.patient_id = PE.person_id
                      LEFT JOIN department d ON T.department_id=d.department_id",
            'where' =>"T.patient_id=$patienId "
            );
        $ds->setup($this->_db, $sql);
        $result = $ds->toArray();
        if(count($result) > 0) {
            return $result[0];
        }

        return array();
	}

}
?>
